from flask import (
    Blueprint,
    request,
    g,
    render_template,
)

from exit import db
from .decorators import login_need
from flask_paginate import Pagination, get_page_parameter
from apps.mall.models import *
from .models import CMSRecord
from .forms import *
from apps.mall.forms import DetailForm
from apps.common.models import *
from utils import restful, common_util, api_util
from datetime import datetime
from apps.api.models import *
import requests
import json
from .views_cms import bp
from sqlalchemy import or_
import ast
from decimal import Decimal


@bp.route('/cms_mall_test/')
def cms_mall_test():
    return restful.success()


# 第二版易货商品
@bp.route('/mall/v2.0/mall_orders_info/')  # 商城订单信息待处理
@login_need
def mall_orders_info2():
    return restful.table_success()


@bp.route('/mall/v2.0/complain_order/', methods=['POST'])     # 申诉处理订单
@login_need
def complain_buyer():
    return restful.success()


@bp.route('/sql_data/')
def sql_data():
    sql = 'SELECT  now() 当前时间,  ifnull(sum(if(t_type=1, num, 0)),0) 未成交买单, ifnull(sum(if(t_type=2, num, 0)),0) 未成交卖单,  (select count(1) from c_mall_buy_deal where create_time >= date(now()) and deal_type=1) 已成交单数,  (select 60/global_params from c_global_params where g_type=9) 当前成交速度, (SELECT SUM(s_num_sell) from c_mall_buy_deal where buyer_id="bXZ4cXumWF76gchBPomzZP" and `status`=0) 刘鹏可卖票总数,  (SELECT SUM(s_num_sell) from c_mall_buy_deal where buyer_id="FgqaxzE86p22YEJyrbyz7S" and `status`=0) 王磊可卖票总数, (SELECT SUM(s_num_sell) from c_mall_buy_deal where buyer_id not in ("bXZ4cXumWF76gchBPomzZP", "FgqaxzE86p22YEJyrbyz7S") and `status`=0 and tn_day=0) 用户今日可卖票总数, (SELECT SUM(s_num_sell) from c_mall_buy_deal where buyer_id not in ("bXZ4cXumWF76gchBPomzZP", "FgqaxzE86p22YEJyrbyz7S") and `status`=0 and tn_day=1) 用户明日可卖票总数 FROM c_mall_buy_order WHERE `status` = 0'
    data_obj = db.session.execute(sql).first()
    str_data = '<h1>当前时间：{}<br/>未成交买单：{}<br/>未成交卖单：{}<br/>已成交单数：{}<br/>当前成交速度：{}<br/><br/>刘鹏可卖票总数：{}<br/>王磊可卖票总数：{}<br/>用户今日可卖票总数：{}<br/>用户明日可卖票总数：{}<br/>'.format(data_obj['当前时间'], data_obj['未成交买单'], data_obj['未成交卖单'], data_obj['已成交单数'], data_obj['当前成交速度'], data_obj['刘鹏可卖票总数'], data_obj['王磊可卖票总数'], data_obj['用户今日可卖票总数'], data_obj['用户明日可卖票总数'])
    return str_data


@bp.route('/create_user_manage/')  # 创建其他用户
@login_need
def create_user_manage():
    return render_template('cms/user_create.html')


@bp.route('/create_user_other/', methods=['POST'])  # 创建其他用户
@login_need
def create_user_other():
    phone = request.form.get('phone')
    other_income = request.form.get('other_income')
    income = request.form.get('income')
    user = User.query.filter_by(phone=phone).first()
    if user:
        return restful.params_error(message='该手机号已被注册')
    if len(phone) != 11:
        return restful.params_error(message='手机号必须11位')
    invite_id = api_util.create_invite()
    create_user = User(
        phone=phone, password=phone, username=phone, nickname=phone,
        other_status=1, other_income=other_income, income=income,
        invite=invite_id,
    )
    db.session.add(create_user)
    db.session.flush()
    system_user = User.query.filter_by(phone='15224897513').first()
    parent2 = User.query.filter_by(id=system_user.p_id).first()
    if parent2:
        create_user.p_id2 = parent2.id
    create_user.p_id = system_user.id
    system_user.team_num += 1
    system_user.direct_num += 1
    if system_user.p_path is None:
        create_user.p_path = system_user.id
    else:
        create_user.p_path = '{},{}'.format(system_user.id, system_user.p_path)
        p_path_list = system_user.p_path.split(',')
        for i in p_path_list:
            parent_user = User.query.filter_by(id=i).first()
            parent_user.team_num += 1

    record = '饭店充值{}'.format(other_income)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=create_user.id)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/update_other_income/', methods=['POST'])    # 饭店消费
@login_need
def update_other_income():
    phone = request.form.get('phone')
    other_income = request.form.get('other_income')
    user = User.query.filter_by(phone=phone).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    other_income = Decimal(other_income)

    record = '饭店原余额<{}> 增加<{}> 剩余<{}>'.format(user.other_income, other_income, user.other_income + other_income)
    user.other_income += other_income
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()

